package com.lboyang.remoting.transport.netty.client;



import com.lboyang.common.dto.NrpcResponse;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description：
 *      服务器未处理的请求
 * @Date 2021/9/11 22:39
 * @author: A.iguodala
 */
public class UnprocessedRequests {
    private static final Map<String, CompletableFuture<NrpcResponse<Object>>> UNPROCESSED_RESPONSE_FUTURES = new ConcurrentHashMap<>();

    /**
     * 防止没有处理的请求
     * @param requestId 请求 ID
     * @param future 异步任务
     */
    public void put(String requestId, CompletableFuture<NrpcResponse<Object>> future) {
        UNPROCESSED_RESPONSE_FUTURES.put(requestId, future);
    }

    /**
     * 处理未处理的请求
     * @param rpcResponse
     */
    public void complete(NrpcResponse<Object> rpcResponse) {
        CompletableFuture<NrpcResponse<Object>> future = UNPROCESSED_RESPONSE_FUTURES.remove(rpcResponse.getRequestId());
        if (null != future) {
            future.complete(rpcResponse);
        } else {
            throw new IllegalStateException();
        }
    }
}
